<template>
    <div>
        <el-dialog width="90%" :visible.sync="editVisible" :close-on-click-modal="false" :close-on-press-escape="false" modal-append-to-body :before-close="handleClose" class="review-drawer">
            <div class="edit-tab-title">编辑自定义组件</div>
            <div class="edit-content">
                <div class="edit-tab">
                    <div class="single-tab">
                        <span class="tab-name">
                            <el-upload :auto-upload="false" accept=".html,.HTML,.css,.CSS,.js,.JS,.png,.PNG,.jpg,.JPG,.jpeg,.JPEG,.gif,.GIF" :multiple="false" ref="upload" action="#" :on-change="uploadSimpleFile">
                                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                            </el-upload>
                        </span>
                    </div>
                    <div class="single-tab" :class="activeIndex === index ? 'active' : ''" v-for="(item, index) in tab" :key="index" @click="tabChange(item, index)">
                        <span class="tab-name">{{item.name}}</span>
                        <span class="delete-child">
                            <i class="el-icon-close" @click.stop="deleteSimpleFile(item, index)"></i>
                        </span>
                    </div>
                </div>
                <div class="textarea-content">
                    <div class="picture" v-if="picVisible">
                        <img :src="picSrc" />
                    </div>
                    <div v-show="lang === 'html'">
                        <textarea ref="myEditor" class="textarea" v-model="code"></textarea>
                    </div>
                    <div v-show="lang === 'javascript'">
                        <textarea ref="jSEditor" class="textarea" v-model="code"></textarea>
                    </div>
                    <div v-show="lang === 'css'">
                        <textarea ref="cssEditor" class="textarea" v-model="code"></textarea>
                    </div>
                </div>
            </div>
            <div slot="footer" class="dialog-footer" v-if="!picVisible">
                <div class="main-base-row-item-grid dialog-footer-row">
                    <div class="edit-data-btn-cancel" @click="closeDialog">取&nbsp;消</div>
                    <div class="edit-data-btn" @click="completeEdit">确&nbsp;定</div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
// 编辑器相关
import codeMirror from 'codemirror';
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/material-darker.css';
import 'codemirror/addon/hint/show-hint.css';
import 'codemirror/addon/edit/matchbrackets';
import 'codemirror/addon/selection/active-line';
import 'codemirror/mode/javascript/javascript';
import 'codemirror/mode/css/css';
import 'codemirror/mode/htmlmixed/htmlmixed';
import template from '@/js/element/template.js';
import url from '@/js/util/url.js';
import user from '@/js/util/user.js';
import coder from '@/js/main/coder.js';
import message from '@/js/util/message.js';
import config from '@/js/util/config.js';
import JQuery from 'jquery';

export default {
    data() {
        return {
            CodeMirror: window.CodeMirror || codeMirror,
            editorText: null,
            editorJS: null,
            editorCss: null,
            template: template,
            theme: 'twilight',
            code: '',
            tab: [],
            activeIndex: 0,
            editVisible: false,
            picVisible: false,
            picSrc: '',
            id: '',
            editComponent: {},
            lang: '',
            editorFile: {},
            editorOption: {
                tabSize: 4,
                lineNumbers: true,
                line: true,
                indentWithTabs: true,
                smartIndent: true,
                autoRefresh: true,
                theme: 'material-darker',
                lineWrapping: true,
                foldGutter: true,
                gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
                matchBrackets: true,
                autoCloseBrackets: true,
                extraKeys: {
                    'Ctrl-Space': 'autocomplete'
                }
            }
        };
    },
    mounted() {
        coder.initialize(this);
    },
    methods: {
        initEditorText(codeType) {
            let _this = this;
            this.$nextTick(() => {
                if (codeType === 'HTML') {
                    this.editorText = this.CodeMirror.fromTextArea(_this.$refs.myEditor, this.editorOption);
                    this.editorText.setSize('100%', '100%');
                } else if (codeType === 'JS') {
                    this.editorJS = this.CodeMirror.fromTextArea(_this.$refs.jSEditor, this.editorOption);
                    this.editorJS.setSize('100%', '100%');
                } else if (codeType === 'CSS') {
                    this.editorCss = this.CodeMirror.fromTextArea(_this.$refs.cssEditor, this.editorOption);
                    this.editorCss.setSize('100%', '100%');
                }
            });
        },
        uploadSimpleFile(file) {
            let exist = false;
            for (let i = 0; i < this.tab.length; i++) {
                if (this.tab.name === file.name) {
                    exist = true;
                    break;
                }
            }
            if (!exist) {
                let uploadSimpleData = new FormData();
                uploadSimpleData.set('token', user.getToken());
                uploadSimpleData.set('id', this.id);
                uploadSimpleData.set('file', file.raw);
                let result = JQuery.ajax({
                    url: url.addSimpleFile,
                    async: false,
                    contentType: false,
                    processData: false,
                    type: 'POST',
                    data: uploadSimpleData
                }).responseJSON;
                if (result.state.code) {
                    message.message('添加成功！', 'success');
                    exist = false;
                    template.resetSimpleList();
                }
            } else {
                exist = false;
            }
        },
        open() {
            this.editVisible = true;
        },
        setID(id) {
            this.id = id;
            this.getTabList(id);
        },
        handleClose(done) {
            done();
            this.activeIndex = 0;
            this.editVisible = false;
        },
        closeDialog() {
            this.activeIndex = 0;
            this.editVisible = false;
        },
        deleteSimpleFile(item) {
            let _this = this;
            message.confirm(
                '确定删除该组件么？',
                '',
                function() {
                    template.removeSimpleFile(
                        item.id,
                        function() {
                            _this.activeIndex = 0;
                            _this.getTabList(_this.id);
                            _this.getCodeContent(_this.editComponent.data.file[0]);
                        },
                        function() {
                            message.message('删除失败！', 'info');
                        }
                    );
                },
                function() {
                    message.message('已取消删除！', 'info');
                }
            );
        },
        getCodeContent(item) {
            this.code = '';
            this.editorFile = item;
            this.lang = '';
            let fileType = item.name.substring(item.name.lastIndexOf('.') + 1).toUpperCase();
            if (fileType === 'PNG' || fileType === 'JPG' || fileType === 'JPEG' || fileType === 'GIF') {
                this.picVisible = true;
                this.lang = '';
                this.picSrc = `${config.getServiceURL('scene')}service/scene/file/download?file=${item.file}`;
            } else if (fileType === 'HTML' || fileType === 'CSS' || fileType === 'JS') {
                this.picVisible = false;
                switch (fileType) {
                    case 'HTML':
                        this.lang = 'html';
                        break;
                    case 'JS':
                        this.lang = 'javascript';
                        break;
                    case 'CSS':
                        this.lang = 'css';
                        break;
                    default:
                        this.lang = '';
                        break;
                }
                let param = {
                    file: item.file
                };
                let resData = url.getSimpleFile(param);
                if (!resData) {
                    return;
                }
                this.$nextTick(() => {
                    this.code = resData;
                    if (fileType === 'HTML') {
                        if (this.editorText === null) {
                            this.editorOption.mode = 'htmlmixed';
                            this.initEditorText(fileType);
                        } else {
                            this.editorText.setValue(this.code);
                        }
                    }
                    if (fileType === 'JS') {
                        if (this.editorJS === null) {
                            this.editorOption.mode = 'javascript';
                            this.initEditorText(fileType);
                        } else {
                            this.editorJS.setValue(this.code);
                        }
                    }
                    if (fileType === 'CSS') {
                        if (this.editorCss === null) {
                            this.editorOption.mode = 'css';
                            this.initEditorText(fileType);
                        } else {
                            this.editorCss.setValue(this.code);
                        }
                    }
                });
            }
        },
        tabChange(item, index) {
            window.stop();
            this.activeIndex = index;
            this.getCodeContent(item);
        },
        completeEdit() {
            let editCode = '';
            switch (this.lang) {
                case 'html':
                    editCode = this.editorText.getValue();
                    break;
                case 'javascript':
                    editCode = this.editorJS.getValue();
                    break;
                case 'css':
                    editCode = this.editorCss.getValue();
                    break;
            }
            let blob = new Blob([editCode]);
            let elementFile = new File([blob], this.editorFile.name);
            let editSimpleData = new FormData();
            editSimpleData.set('token', user.getToken());
            editSimpleData.set('id', this.editorFile.id);
            editSimpleData.set('file', elementFile);
            let result = JQuery.ajax({
                url: url.uodateSimpleFile,
                async: false,
                contentType: false,
                processData: false,
                type: 'POST',
                data: editSimpleData
            }).responseJSON;
            if (result.state.code) {
                message.message('修改成功！', 'success');
            }
        },
        getTabList(id) {
            this.tab = [];
            this.editComponent = template.baseElementMap[id];
            this.tab = this.editComponent.data.file;
            this.getCodeContent(this.editComponent.data.file[0]);
        }
    }
};
</script>

<style lang='scss' scoped>
.review-drawer {
    padding: 0 20px;
    ::v-deep.el-dialog {
        display: flex;
        flex-direction: column;
        height: 70%;
        background: #212121;
    }
    ::v-deep.el-dialog .el-dialog__body {
        flex: 1;
        padding: 0;
        overflow: hidden;
    }
    ::v-deep.el-dialog__header {
        padding: 0 10px;
    }
    ::v-deep.el-dialog__headerbtn {
        top: 15px;
    }
    .dialog-footer {
        float: right;
        width: 180px;
    }
    .dialog-footer-row {
        grid-template-columns: repeat(2, 50%);
    }
}
.edit-tab-title {
    height: 40px;
    line-height: 40px;
    border-bottom: 1px solid #ffffff0f;
    margin: 0px 20px 0;
}
.edit-content {
    display: flex;
    width: 100%;
    height: calc(100% - 52px);
    border-bottom: 1px solid #000000cc;
    .edit-tab {
        width: 200px;
        border-right: 1px solid #000000;
        overflow: auto;
        .single-tab {
            width: 100%;
            height: 50px;
            line-height: 50px;
            text-align: center;
            cursor: pointer;
            display: flex;
            border-bottom: 1px solid #000000cc;
        }
        .tab-name {
            height: 50px;
            width: 160px;
            overflow: hidden;
            display: inline-block;
            white-space: nowrap;
            text-overflow: ellipsis;
            padding: 0 5px;
        }
        .delete-child {
            padding: 0 5px;
            text-align: center;
            height: 50px;
            display: inline-block;
        }
        .active {
            background: #000000cc;
        }
    }
}
.textarea-content {
    height: 100%;
    width: calc(100% - 201px);
    overflow: auto;
    .picture {
        width: 100%;
        height: 100%;
        padding: 20px;
        img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }
    }
    .code {
        width: 100%;
        height: 100%;
        div {
            width: 100%;
            height: 100%;
        }
    }
}
.textarea {
    font-size: 14px;
    background: #252d42;
}
.edit-data-btn {
    height: 30px;
    line-height: 30px;
    background: #3664ece6;
    color: $FontWhite;
    text-align: center;
    border-radius: 5px;
    cursor: pointer;
    &:hover {
        background: #3664ecff;
    }
}

.edit-data-btn-cancel {
    height: 30px;
    line-height: 30px;
    background: #ffffff0f;
    color: $FontWhite;
    text-align: center;
    border-radius: 5px;
    cursor: pointer;
    &:hover {
        background: #ffffff33;
    }
}
</style>
<style>
.CodeMirror-vscrollbar {
    display: none !important;
}
</style>
